package com.bot.backend.consumer;

import com.alibaba.fastjson.JSONObject;
import com.bot.backend.consumer.utils.JwtAuthentication;
import com.bot.backend.mapper.RecordMapper;
import com.bot.backend.mapper.SnakeMapper;
import com.bot.backend.mapper.UserMapper;
import com.bot.backend.pojo.Snake;
import com.bot.backend.pojo.User;
import com.bot.backend.utils.Game;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾
public class WebSocketServer {
    // 将用户id 映射到每个websocket实例，以便通过用户id找到其对应的websocket
    // static 所有实例访问同一个哈希表
    final public static ConcurrentHashMap<Integer, WebSocketServer> users = new ConcurrentHashMap<>();


    private User user;

    // 用户从后端向前端发送消息
    private Session session = null;

    public Game game = null; // 创建全局地图
    public static RecordMapper recordMapper;
    /*
    * 注入userMapper的方法
    * */
    public static UserMapper userMapper;

    public static RestTemplate restTemplate;

    private final static String addPlayerUrl = "http://127.0.0.1:3001/player/add/";
    private final static String removePlayerUrl = "http://127.0.0.1:3001/player/remove/";

    private static SnakeMapper snakeMapper;

    @Autowired
    public void setSnakeMapper(SnakeMapper snakeMapper) {
        WebSocketServer.snakeMapper = snakeMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        WebSocketServer.restTemplate = restTemplate;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    /*
        每来一个请求都创建一个线程维护这个请求
        * */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        // 建立连接
        this.session = session; // 建立连接时将session存储
        int userId = JwtAuthentication.getUserIdBytoken(token);
        this.user = userMapper.selectById(userId);
        if (this.user != null) {
            users.put(userId, this);

        } else {
            try {
                this.session.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.err.println(this.user);

    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.err.println("disconnected");

        // 关闭连接时删除该用户
        if (this.user != null) {
            users.remove(this.user.getId());
        }
    }

    public static void startGame(Integer aId, Integer bId, Integer aSnakeId, Integer bSnakeId) {
        System.err.println("start game ... ");
        User a = userMapper.selectById(aId);
        User b = userMapper.selectById(bId);
        Snake snakeA = snakeMapper.selectById(aSnakeId);
        Snake snakeB = snakeMapper.selectById(bSnakeId);

        Game game = new Game(20, 31, 50, a.getId(), b.getId(), snakeA, snakeB);
        game.createMap();

        if (users.get(a.getId()) != null) {
            users.get(a.getId()).game = game;
        }

        if (users.get(b.getId()) != null) {
            users.get(b.getId()).game = game;
        }


        game.start(); // 开启多线程
        JSONObject respGame = new JSONObject();
        respGame.put("a_id", game.getPlayerA().getId());
        respGame.put("a_sx", game.getPlayerA().getSx());
        respGame.put("a_sy", game.getPlayerA().getSy());
        respGame.put("b_id", game.getPlayerB().getId());
        respGame.put("b_sx", game.getPlayerB().getSx());
        respGame.put("b_sy", game.getPlayerB().getSy());
        respGame.put("map", game.getG());

        JSONObject respA = new JSONObject();
        respA.put("event", "start-matching");
        respA.put("opponent_username", b.getUsername());
        respA.put("opponent_photo", b.getPhoto());
        respA.put("game", respGame);
        if (users.get(a.getId()) != null) {
            users.get(a.getId()).sendMessage(respA.toJSONString()); // 获取a的连接，将消息发送到前端
        }


        JSONObject respB = new JSONObject();
        respB.put("event", "start-matching");
        respB.put("opponent_username", a.getUsername());
        respB.put("opponent_photo", a.getPhoto());
        respB.put("game", respGame);
        if (users.get(b.getId()) != null) {
            users.get(b.getId()).sendMessage(respB.toJSONString()); // 获取b的连接，将消息发送到前端
        }

    }

    private void startMacthing(Integer snakeId) {
        System.err.println("start_matching...");
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        data.add("rating", this.user.getRating().toString());
        data.add("snake_id", snakeId.toString());
        // 向匹配池发送请求
        restTemplate.postForObject(addPlayerUrl, data, String.class);
    }

    private void stopMatching() {
        System.err.println("stop_matching...");
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", this.user.getId().toString());
        restTemplate.postForObject(removePlayerUrl, data, String.class);
    }

    // 蛇的移动
    private void move(Integer direction) {
        System.err.println("snake move ... ");
        if (this.game.getPlayerA().getId().equals(this.user.getId())) {
            if (this.game.getPlayerA().getSnakeId().equals(-1)) { // 人工操作
                this.game.setNextStepA(direction);
            }
        } else if (this.game.getPlayerB().getId().equals(this.user.getId())) {
            if (this.game.getPlayerB().getSnakeId().equals(-1)) {
                this.game.setNextStepB(direction);
            }

        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息时调用该函数
        System.err.println("receive message!");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event"); // 收到前端发送的event数据
        if ("start_matching".equals(event)) {
            this.startMacthing(data.getInteger("snake_id"));
        } else if ("stop_matching".equals(event)) {
            this.stopMatching();
        } else if ("move".equals(event)) {
            this.move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /*
    * 从后端向前端发送信息
    * */
    public void sendMessage(String message) {
        System.err.println(message);
        // 异步通信过程需要加锁，每次只能发送一个进程, 只有这个进程主动解锁才会进入下一个进程
        synchronized (this.session) {
            try {
                // 将messsage发送到前端
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
